<template>
  <div>
    <van-field v-model="msg">
      <template #button>
        <van-button type="info" @click="btnClick">发送</van-button>
      </template>
    </van-field>
    <van-button @click="closeEvent">关闭</van-button>
  </div>
</template>
<script>
// 1:安装插件
// 2:导入插件
import { io } from 'socket.io-client'
export default {
  data () {
    return {
      socket: '',
      msg: ''
    }
  },
  created () {
    // 3:建立连接
    this.socket = io('http://toutiao.itheima.net', {
      query: {
        token: this.$store.state.tokenObj.token
      },
      transports: ['websocket']
    })
    // 监听是否连接成功
    this.socket.on('connect', () => {
      console.log('连接成功')
    })
    // 4:接收消息
    this.socket.on('message', data => {
      console.log('服务端返回消息', data)
    })
    // 关闭的监听
    this.socket.on('disconnect', () => {
      console.log('关闭')
    })
  },
  methods: {
    btnClick () {
      // 5:发送消息
      console.log(this.msg)
      this.socket.emit('message', {
        msg: this.msg,
        timestamp: Date.now()
      })
    },
    closeEvent () {
      this.socket.close()
    }
  }
}
</script>
<style></style>
